/**
 * Global Comments Here                                                                                  
 */
package oa.base.spring;

import java.io.InputStream;
import java.util.Properties;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author lilang
 *
 */
public class ApplicationPropertiesHolder {

    private static Log logger = LogFactory.getLog(ApplicationPropertiesHolder.class);

    
    private static Properties props = null;

    private static boolean initialized = false;

    
    private ApplicationPropertiesHolder() {
		super();
	}

	public static void initApplicationProperties() {
        if (!initialized) {
        	props = new Properties();
            InputStream in = null;
            try {
                in = ApplicationPropertiesHolder.class.getClassLoader()
                        .getResourceAsStream("application.properties");
                // logger.debug("file inputstream=" + in);
                Properties propsDefault = new Properties();
                propsDefault.load(in);
                for (Entry<Object, Object> entry : propsDefault.entrySet()) {
                    // logger.debug(entry.getKey() + "=" + entry.getValue());
                    props.put(entry.getKey(), entry.getValue());
                }
            } catch (Exception e) {
            	logger.error("Can't load application.properties");
            }
            try {
                in = ApplicationPropertiesHolder.class.getClassLoader().getResourceAsStream("webapp.properties");
                Properties propsApp = new Properties();
                propsApp.load(in);
                for (Entry<Object, Object> entry : propsApp.entrySet()) {
                    logger.info(entry.getKey() + "=" + entry.getValue());
                    props.put(entry.getKey(), entry.getValue());
                }
            } catch (Exception e) {
                logger.error("Can't load webapp.properties,use default application.properties");
            }
            initialized = true;
        }
    }

    public static String getProperty(String key) {
    	if(null == props){
    		initApplicationProperties();
    	}
        return (String) props.get(key);
    }
    
    public static void main(String[] args) {
        ApplicationPropertiesHolder.initApplicationProperties();
        for (Entry<Object, Object> entry : props.entrySet()) {
        	System.out.println(entry.getKey() + "=" + entry.getValue());
            logger.info(entry.getKey() + "=" + entry.getValue());
        }
    }
}
